package studychinese.activity;

import android.Manifest;
import android.app.Dialog;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.resource.bitmap.CenterCrop;
import com.hschinese.pronunciation.R;
import com.hschinese.pronunciation.widget.GlideCircleTransform;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.HttpParams;
import com.lzy.okgo.model.Response;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.qqtheme.framework.picker.DatePicker;
import cn.qqtheme.framework.util.ConvertUtils;
import de.hdodenhof.circleimageview.CircleImageView;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnNeverAskAgain;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.RuntimePermissions;
import studychinese.callback.DialogCallback;
import studychinese.config.AppUrl;
import studychinese.config.ConFigTag;
import studychinese.config.Url;
import studychinese.model.RegisterBean;
import studychinese.model.UpdataPersonInfoBean;
import studychinese.model.UserBean;
import studychinese.utils.TimeUtil;
import studychinese.utils.ToastUtils;
import studychinese.utils.Utils;
@RuntimePermissions
public class PersonalInformationActivity extends BaseAcitivity  {
    @Bind(R.id.title_tv)
    TextView titleTv;
    @Bind(R.id.iv_personinformation_icon)
    ImageView ivPersoninformationIcon;
    @Bind(R.id.tv_personin_nikename)
    TextView tvPersoninNikename;
    @Bind(R.id.iv_person_fanhui)
    ImageView ivPersonFanhui;
    @Bind(R.id.tv_personin_sex)
    TextView tvPersoninSex;
    @Bind(R.id.iv_person_fanhui1)
    ImageView ivPersonFanhui1;
    @Bind(R.id.tv_personin_birthday)
    TextView tvPersoninBirthday;
    @Bind(R.id.iv_person_fanhui2)
    ImageView ivPersonFanhui2;
    protected static final int CHOOSE_PICTURE = 0;
    protected static final int TAKE_PICTURE = 1;
    private static final int CROP_SMALL_PICTURE = 2;
    private static final int MY_PERMISSIONS_REQUEST_CALL_CAMERA = 4;//请求码，自己定义
    protected static Uri tempUri;
    private List<String> list=new ArrayList<>();
    private String user_age;
    private String user_agent;
    private String user_nickname;


    @Override
    protected int setContainer() {
        return R.layout.activity_personal_information;
    }

    @Override
    public void innitView(){
        ButterKnife.bind(this);
        titleTv.setText("个人信息");
        user_age = UserBean.getInfor().getUser_age();
        user_agent = UserBean.getInfor().getUser_agent();
        user_nickname = UserBean.getInfor().getUser_nickname();
        long time = UserBean.getInfor().getCreate_time();
        String user_image = UserBean.getInfor().getUser_image();
        if("".equals(user_image)){
            Glide.with(this).load(R.mipmap.my_photo_normal).into(ivPersoninformationIcon);


        }else {
            Glide.with(this)
                    .load(user_image)
                    .transform(new CenterCrop(this),new GlideCircleTransform(this))
                    .crossFade()
                    .into(ivPersoninformationIcon);
//            Glide.with(this).load(user_image).into(ivPersoninformationIcon);

        }
        if (user_nickname.equals(""))
        {
            tvPersoninNikename.setText(  ("用户"+TimeUtil.Tests1(time)));
        }
        else
        {
            tvPersoninNikename.setText(user_nickname);
        }
        if (user_agent.equals(""))
        {
            tvPersoninSex.setText("性别");
        }else {
            if(user_agent.equals("1")){
                tvPersoninSex.setText("男");
            }else {
                tvPersoninSex.setText("女");
            }

        }

        if (user_age.equals(""))
        {
            tvPersoninBirthday.setText("生日");
        }
        else
        {

            tvPersoninBirthday.setText(TimeUtil.Tests(Long.parseLong(user_age)));

        }
    }

    private void showPhoto(List<String> list, final boolean isCarmer) {
        final Dialog bottomDialog = new Dialog(this, R.style.BottomDialog);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_seletephoto, null);
        TextView tv_dialog_seletphoto_paizhao = (TextView) contentView.findViewById(R.id.tv_dialog_seletphoto_paizhao);
        TextView tv_dialog_seletphoto_xiangce = (TextView) contentView.findViewById(R.id.tv_dialog_seletphoto_xiangce);
        TextView tv_dialog_cancle = (TextView) contentView.findViewById(R.id.tv_dialog_cancle);
        if(list.size()>1){
            tv_dialog_seletphoto_paizhao.setText(list.get(0));
            tv_dialog_seletphoto_xiangce.setText(list.get(1));
        }
        tv_dialog_seletphoto_paizhao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isCarmer){
                    PersonalInformationActivityPermissionsDispatcher.callCameraWithPermissionCheck(PersonalInformationActivity.this);

//                    callCamera();

                }else {
                    setUpdata("1",2);
                    tvPersoninSex.setText("男");
                }
                bottomDialog.dismiss();

            }
        });
        tv_dialog_seletphoto_xiangce.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isCarmer){
                    PersonalInformationActivityPermissionsDispatcher.getPhotoWithPermissionCheck(PersonalInformationActivity.this);
                }else {
                    tvPersoninSex.setText("女");
                    setUpdata("2",2);
                }
                bottomDialog.dismiss();
            }
        });
        tv_dialog_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bottomDialog.dismiss();
            }
        });
        bottomDialog.setContentView(contentView);
        ViewGroup.LayoutParams layoutParams = contentView.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        contentView.setLayoutParams(layoutParams);
        bottomDialog.getWindow().setGravity(Gravity.BOTTOM);
        bottomDialog.setCanceledOnTouchOutside(true);
        bottomDialog.getWindow().setWindowAnimations(R.style.BottomDialog_Animation);
        bottomDialog.show();
    }
@NeedsPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
     void getPhoto() {
        Intent openAlbumIntent = new Intent(
                Intent.ACTION_PICK, MediaStore.Images.Media. EXTERNAL_CONTENT_URI);
        openAlbumIntent.setType("image/*");
        startActivityForResult(openAlbumIntent, CHOOSE_PICTURE);
    }

    @NeedsPermission({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
     void callCamera() {
        Intent openCameraIntent = new Intent(

                MediaStore.ACTION_IMAGE_CAPTURE);
        tempUri = Uri.fromFile(new File(Environment
                .getExternalStorageDirectory(), "image.jpg"));
        // 指定照片保存路径（SD卡），image.jpg为一个临时文件，每次拍照后这个图片都会被替换
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, tempUri);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
    }
    @OnPermissionDenied({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showDeniedForCamera() {
//        Toast.makeText(this, "拒绝了权限", Toast.LENGTH_SHORT).show();
    }
    @OnNeverAskAgain({Manifest.permission.CAMERA,Manifest.permission.WRITE_EXTERNAL_STORAGE})
    void showNeverAskForCamera() {
        Toast.makeText(this, R.string.define_permission, Toast.LENGTH_SHORT).show();
    }
    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // NOTE: delegate the permission handling to generated method
        PersonalInformationActivityPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
        /*if (requestCode == MY_PERMISSIONS_REQUEST_CALL_CAMERA) {
            //grantResults授权结果
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //成功，开启摄像头
                callCamera();
            } else {
                //授权失败
                Toast.makeText(PersonalInformationActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);*/
    }
 /*  *//* @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        //判断请求码
        if (requestCode == MY_PERMISSIONS_REQUEST_CALL_CAMERA) {
            //grantResults授权结果
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                //成功，开启摄像头
                callCamera();
            } else {
                //授权失败
                Toast.makeText(PersonalInformationActivity.this, "Permission Denied", Toast.LENGTH_SHORT).show();
            }
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }*/
    @OnClick({R.id.left_img, R.id.iv_personinformation_icon, R.id.rl_slearning_nikename, R.id.rl_slearning_sex, R.id.rl_slearning_birthday})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.left_img:
                this.finish();
                break;
            case R.id.iv_personinformation_icon:
                list.clear();
                list.add("拍照");
                list.add("选择照片");
                showPhoto(list,true);

                break;
            case R.id.rl_slearning_nikename:
                initDialog();
                break;
            case R.id.rl_slearning_sex:
                list.clear();
                list.add("男");
                list.add("女");
                showPhoto(list,false);
                break;
            case R.id.rl_slearning_birthday:
                onYearMonthDayPicker();
                break;
        }
    }




    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) { // 如果返回码是可以用的
            switch (requestCode) {
                case TAKE_PICTURE:
                    startPhotoZoom(tempUri); // 开始对图片进行裁剪处理
                    break;
                case CHOOSE_PICTURE:
                    startPhotoZoom(data.getData()); // 开始对图片进行裁剪处理
                    break;
                case CROP_SMALL_PICTURE:
                    if (data != null) {
                        setImageToView(data); // 让刚才选择裁剪得到的图片显示在界面上
                    }
                    break;
            }
        }
    }

    /**
     * 裁剪图片方法实现
     *
     * @param uri
     */
    protected void startPhotoZoom(Uri uri) {
        if (uri == null) {
            Log.i("tag", "The uri is not exist.");
        }
        tempUri = uri;
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        // 设置裁剪
        intent.putExtra("crop", "true");
        // aspectX aspectY 是宽高的比例
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        // outputX outputY 是裁剪图片宽高
        intent.putExtra("outputX", 150);
        intent.putExtra("outputY", 150);
        intent.putExtra("return-data", true);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
        startActivityForResult(intent, CROP_SMALL_PICTURE);
    }


    protected void setImageToView(Intent data) {
        Bundle extras = data.getExtras();
        if (extras != null) {
            Bitmap photo = extras.getParcelable("data");
            photo = Utils.toRoundBitmap(photo, tempUri); // 这个时候的图片已经被处理成圆形的了
            ivPersoninformationIcon.setImageBitmap(photo);
            uploadPic(photo);
        }
    }
    private void uploadPic(Bitmap bitmap) {
        // 上传至服务器
        // ... 可以在这里把Bitmap转换成file，然后得到file的url，做文件上传操作
        // 注意这里得到的图片已经是圆形图片了
        // bitmap是没有做个圆形处理的，但已经被裁剪了

        String imagePath = Utils.savePhoto(bitmap, Environment
                .getExternalStorageDirectory().getAbsolutePath(), String
                .valueOf(System.currentTimeMillis()));
        if (imagePath != null) {

            File file = new File(imagePath);
            if (!file.exists()) {
                try {
                    file.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            OkGo.<String>post(AppUrl.getAppUrl(Url.REGISTER_UPLOADIMAGE)).params("user_id",UserBean.getInfor().getUser_id())

                    .params("filetype",1)
                    .params("fileName",file)
                    .execute(new DialogCallback<String>(this,false) {
                @Override
                public void onSuccess(Response<String> response) {

                    try {
                        JSONObject jsonObject = new JSONObject(response.body());
                        String state = jsonObject.optString("state");
                        String message = jsonObject.optString("message");
                        if(state== ConFigTag.state){
                            JSONObject data = jsonObject.getJSONObject("data");
                            RegisterBean.DataBean infor = UserBean.getInfor();
                            infor .setUser_image(data.optString("user_image"));
                            UserBean.putUserBean(infor);

                        }
                       ToastUtils.showShort(message);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            });
        }
    }
    public void onYearMonthDayPicker() {
        final DatePicker picker = new DatePicker(this);
        picker.setTopPadding(ConvertUtils.toPx(this, 10));
        picker.setRangeEnd(2111, 1, 11);
        picker.setRangeStart(1945, 1, 1);
        picker.setSelectedItem(1990, 10, 14);
        picker.setLabel("年","月","日");
        picker.setOffset(2);
        picker.setDividerVisible(true);
        picker.setLineSpaceMultiplier(3);
        picker.setDividerColor(Color.WHITE);
        picker.setTextSize(18);
        picker.setLineColor(Color.WHITE);
        picker.setTextColor(Color.WHITE,Color.WHITE);
        picker.setCycleDisable(false);
        picker.setTitleText("");
        picker.setDividerRatio(0);
        picker.setSubmitTextColor(Color.WHITE);
        picker.setCancelTextColor(Color.WHITE);

        picker.setBackgroundColor(this.getResources().getColor(R.color.back_theme));
        picker.setTopBackgroundColor(this.getResources().getColor(R.color.back_theme));
        picker.setOnDatePickListener(new DatePicker.OnYearMonthDayPickListener() {
            @Override
            public void onDatePicked(String year, String month, String day) {
                String birday=year + "-" + month+ "-" + day;
                tvPersoninBirthday.setText(birday);

                try {
                    long l = TimeUtil.StringToTime(year + "-" + month + "-" + day);
                    setUpdata(l+"",3);
                } catch (ParseException e) {
                    e.printStackTrace();
                }

            }


        });

       picker.show();
    }
    private void setUpdata(String str,int number) {
        HttpParams httpParams = new HttpParams();
        if(1==number) {
            httpParams.put("user_nickname",str);
        }else if(2==number) {
            httpParams.put("user_agent",str);
        }else if(3==number) {
            httpParams.put("user_age",str);
        }
        httpParams.put("user_id",UserBean.getInfor().getUser_id());
        OkGo.<String>post(AppUrl.getAppUrl(Url.REGISTER_UPDATEUSERINFO)).params(httpParams).execute(new DialogCallback<String>(this,false) {
            @Override
            public void onSuccess(Response<String> response) {
                UpdataPersonInfoBean updataPersonInfoBean = JSON.parseObject(response.body(), UpdataPersonInfoBean.class);
                if(updataPersonInfoBean.getState().equals(ConFigTag.state)){
                    UpdataPersonInfoBean.DataBean data = updataPersonInfoBean.getData();
                    RegisterBean.DataBean infor = UserBean.getInfor();
                    infor.setUser_nickname(data.getUser_nickname());
                    infor.setUser_age(data.getUser_age());
                    infor.setUser_agent(data.getUser_agent());
                    UserBean.putUserBean(infor);
                }else {
                    ToastUtils.showShort(updataPersonInfoBean.getMessage());
                }
            }
        });

    }
    private void initDialog() {
        final Dialog checkUpdateDialog = new Dialog(this);
        View view = LayoutInflater.from(this).inflate(R.layout.create_edittext_dialog, null);
        final EditText cancelTv = (EditText) view.findViewById(R.id.text_info_nikename);

        Button btn_save_pop = (Button) view.findViewById(R.id.btn_save_pop);

        btn_save_pop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
              String  ednikname = cancelTv.getText().toString();
                tvPersoninNikename.setText(ednikname);
                checkUpdateDialog.dismiss();
                setUpdata(ednikname,1);

            }
        });
        checkUpdateDialog.setContentView(view);
        checkUpdateDialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        checkUpdateDialog.setCanceledOnTouchOutside(false);
        //checkUpdateDialog.setCancelable(true);
        checkUpdateDialog.show();
    }
}
